package org.studiox.graph.persistence.spring.jdbc.dao.impl;

import org.springframework.jdbc.core.JdbcTemplate;
import org.studiox.graph.persistence.model.GraphEdgeDO;
import org.studiox.graph.persistence.spring.jdbc.dao.GraphEdgeDao;
import org.studiox.graph.persistence.spring.jdbc.rowmapper.GraphEdgeDOMapper;

import java.util.List;

public class GraphEdgeDaoImpl implements GraphEdgeDao {

  private JdbcTemplate jdbcTemplate;

  public GraphEdgeDaoImpl(JdbcTemplate jdbcTemplate) {
    this.jdbcTemplate = jdbcTemplate;
  }

  public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
    this.jdbcTemplate = jdbcTemplate;
  }

  @Override
  public List<GraphEdgeDO> findAll() {
    String sql = "select * from graph_edge";
    return jdbcTemplate.query(sql, new GraphEdgeDOMapper());
  }

  @Override
  public int save(GraphEdgeDO graphEdgeDO) {
    String sql =
        "insert into graph_edge(content,type,owner,source_vertex_uniq,target_vertex_uniq,"
            + "janus_edge_id,source_janus_vertex_id,target_janus_vertex_id) values (?,?,?,?,?,?,?,?)";
    Object[] obj =
        new Object[] {
          graphEdgeDO.getContent(),
          graphEdgeDO.getType(),
          graphEdgeDO.getOwner(),
          graphEdgeDO.getSourceVertexUniq(),
          graphEdgeDO.getTargetVertexUniq(),
          graphEdgeDO.getJanusEdgeId(),
          graphEdgeDO.getSourceJanusVertexId(),
          graphEdgeDO.getTargetJanusVertexId()
        };
    return jdbcTemplate.update(sql, obj);
  }

  @Override
  public int update(GraphEdgeDO graphEdgeDO) {
    String sql =
        "update graph_edge set content=?,type=?,owner=?,source_vertex_uniq=?,target_vertex_uniq=?,"
            + "janus_edge_id=?,source_janus_vertex_id=?,target_janus_vertex_id=?,deleted=?,update_time=? where id=?";
    Object[] obj =
        new Object[] {
          graphEdgeDO.getContent(),
          graphEdgeDO.getType(),
          graphEdgeDO.getOwner(),
          graphEdgeDO.getSourceVertexUniq(),
          graphEdgeDO.getTargetVertexUniq(),
          graphEdgeDO.getJanusEdgeId(),
          graphEdgeDO.getSourceJanusVertexId(),
          graphEdgeDO.getTargetJanusVertexId(),
          graphEdgeDO.getDeleted(),
          graphEdgeDO.getUpdateTime(),
          graphEdgeDO.getId()
        };
    return jdbcTemplate.update(sql, obj);
  }

  @Override
  public int delete(Long id) {
    String sql = "delete from graph_edge where id=?";
    return jdbcTemplate.update(sql, id);
  }

  @Override
  public GraphEdgeDO findById(Long id) {
    String sql = "select * from graph_edge where id=?";
    return jdbcTemplate.queryForObject(sql, new GraphEdgeDOMapper(), id);
  }

  @Override
  public int findTotalNum() {
    String sql = "select count(*) from graph_edge";
    return jdbcTemplate.queryForObject(sql, (rs, rowNum) -> rs.getInt(1));
  }
}
